import { useState } from 'react';
import { Card, Typography, Form, Input, Button, Select, message, Table, Space } from 'antd';
import { FileAddOutlined, DownloadOutlined, FileOutlined, PlusOutlined, DeleteOutlined } from '@ant-design/icons';
import { toolAPI } from '../utils/api';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

const PPTGeneratePage = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [slides, setSlides] = useState([{ title: '', content: '' }]);
  const [generatedPPTUrl, setGeneratedPPTUrl] = useState(null);

  // 支持的PPT模板类型
  const templateTypes = [
    { value: 'business', label: '商务模板' },
    { value: 'education', label: '教育模板' },
    { value: 'report', label: '报告模板' }
  ];

  // 处理添加幻灯片
  const handleAddSlide = () => {
    setSlides([...slides, { title: '', content: '' }]);
  };

  // 处理删除幻灯片
  const handleDeleteSlide = (index) => {
    if (slides.length <= 1) {
      message.warning('至少保留一张幻灯片');
      return;
    }
    const newSlides = [...slides];
    newSlides.splice(index, 1);
    setSlides(newSlides);
  };

  // 处理幻灯片内容变更
  const handleSlideChange = (index, field, value) => {
    const newSlides = [...slides];
    newSlides[index][field] = value;
    setSlides(newSlides);
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    const { title, templateType } = values;

    if (!title.trim()) {
      message.error('请输入PPT标题');
      return;
    }

    // 验证幻灯片内容
    const hasValidSlide = slides.some(slide => 
      slide.title.trim() || slide.content.trim()
    );

    if (!hasValidSlide) {
      message.error('请至少添加一张有内容的幻灯片');
      return;
    }

    setLoading(true);

    try {
      const response = await toolAPI.generatePPT({
        title,
        templateType,
        slides
      });

      // 处理响应，创建下载链接
      const blob = new Blob([response.data], {
        type: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'
      });
      const url = window.URL.createObjectURL(blob);
      setGeneratedPPTUrl(url);
      message.success('PPT生成成功！');
    } catch (error) {
      console.error('PPT生成失败:', error);
      message.error(`生成失败: ${error.response?.data?.error || '未知错误'}`);
    } finally {
      setLoading(false);
    }
  };

  // 处理下载
  const handleDownload = () => {
    if (generatedPPTUrl) {
      const link = document.createElement('a');
      link.href = generatedPPTUrl;
      const pptTitle = form.getFieldValue('title') || 'generated_ppt';
      link.download = `${pptTitle}.pptx`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    }
  };

  // 重置表单
  const handleReset = () => {
    form.resetFields();
    setSlides([{ title: '', content: '' }]);
    setGeneratedPPTUrl(null);
  };

  // 幻灯片表格列定义
  const columns = [
    {
      title: '幻灯片序号',
      dataIndex: 'index',
      key: 'index',
      render: (_, __, index) => index + 1
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
      render: (_, record, index) => (
        <Input
          value={record.title}
          onChange={(e) => handleSlideChange(index, 'title', e.target.value)}
          placeholder="幻灯片标题"
          disabled={loading}
        />
      )
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      render: (_, record, index) => (
        <TextArea
          value={record.content}
          onChange={(e) => handleSlideChange(index, 'content', e.target.value)}
          placeholder="幻灯片内容"
          rows={2}
          disabled={loading}
        />
      )
    },
    {
      title: '操作',
      key: 'action',
      render: (_, __, index) => (
        <Space size="middle">
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDeleteSlide(index)}
            disabled={loading || slides.length <= 1}
          >
            删除
          </Button>
        </Space>
      )
    }
  ];

  // 将幻灯片数组转换为表格数据格式
  const tableData = slides.map((slide, index) => ({
    key: index,
    ...slide
  }));

  return (
    <Card className="tool-page">
      <Title level={2}>PPT生成工具</Title>
      
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSubmit}
        className="form-section"
        initialValues={{ templateType: 'business' }}
      >
        <Form.Item
          label="PPT标题"
          name="title"
          rules={[{ required: true, message: '请输入PPT标题' }]}
          className="form-section"
        >
          <Input 
            placeholder="请输入PPT标题"
            disabled={loading}
          />
        </Form.Item>

        <Form.Item
          label="模板类型"
          name="templateType"
          rules={[{ required: true, message: '请选择模板类型' }]}
          className="form-section"
        >
          <Select 
            placeholder="请选择模板类型"
            disabled={loading}
            style={{ width: '100%' }}
          >
            {templateTypes.map(template => (
              <Option key={template.value} value={template.value}>
                {template.label}
              </Option>
            ))}
          </Select>
        </Form.Item>

        {/* 幻灯片管理 */}
        <div className="slides-section">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <Text strong>幻灯片管理</Text>
            <Button 
              type="dashed" 
              onClick={handleAddSlide}
              icon={<PlusOutlined />}
              disabled={loading || slides.length >= 50} // 限制最大幻灯片数量
            >
              添加幻灯片
            </Button>
          </div>
          
          <Table
            dataSource={tableData}
            columns={columns}
            pagination={false}
            size="small"
            scroll={{ y: 400 }}
            rowKey="key"
          />
        </div>

        <div className="button-group">
          <Button type="primary" htmlType="submit" loading={loading} icon={<FileOutlined />}>
            生成PPT
          </Button>
          <Button onClick={handleReset} disabled={loading}>
            重置
          </Button>
        </div>
      </Form>

      {/* 生成结果展示 */}
      {generatedPPTUrl && (
        <div className="result-section">
          <Title level={3}>生成结果</Title>
          <Card className="ppt-result">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <div>
                <Text strong>PPT文件已生成</Text>
                <p style={{ marginTop: '8px' }}>点击下方按钮下载您的PPT文件。</p>
              </div>
              <Button 
                type="primary" 
                icon={<DownloadOutlined />}
                onClick={handleDownload}
              >
                下载PPT
              </Button>
            </div>
          </Card>
        </div>
      )}
    </Card>
  );
};

export default PPTGeneratePage;